<template>
  <section v-if="length > 0">
    <el-row v-for="(item, index) in source" :key="index">
      <el-col :span="19">
        <variable-edit
          :value="source[index]"
          @input="handleInput(index, arguments)"
        />
      </el-col>
      <el-col :span="5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          @click="remove(index)"
        ></el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-plus"
          @click="add(index)"
        ></el-button>
      </el-col>
    </el-row>
  </section>
  <el-row v-else>
    <el-col :span="24">
      <el-button
        type="primary"
        icon="el-icon-circle-plus"
        @click="add(0)"
      ></el-button>
    </el-col>
  </el-row>
</template>

<script>
import VariableEdit from "./VariableEdit.vue";
// 论一个列表编辑器的正确写法
export default {
  components: { VariableEdit },
  name: "VariableList",
  props: {
    type: {
      type: Number,
      default() {
        return 1;
      }
    },
    value: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
    source() {
      return this.value || [];
    },
    length() {
      return this.source.length || 0;
    }
  },
  methods: {
    handleInput(index, [value]) {
      let dataList = [...this.source];
      dataList.splice(index, 1, value);
      this.$emit("input", dataList);
    },
    add(index) {
      let dataList = [...this.source];
      dataList.splice(index + 1, 0, { type: this.type });
      this.$emit("input", dataList);
    },
    remove(index) {
      let dataList = [...this.source];
      dataList.splice(index, 1);
      this.$emit("input", dataList);
    }
  }
};
</script>

<style scoped>
.el-button {
  padding: 4px 6px;
  margin: 6px 0px 6px 6px;
}
</style>
